package me.eddiechow.interview;

/**
 * @description: 线程顺序执行控制（线程之间的 wait notify通信）
 * @author: zhoudi
 * @date: 2017/6/12 22:15
 */
public class ThreadExecuteOrderTest {

    private static volatile boolean isThread1 = true;

    static class Thread1 implements Runnable{
        public void run() {
            synchronized (ThreadExecuteOrderTest.class){
                while (!isThread1){
                    try {
                        ThreadExecuteOrderTest.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                for (int i = 0; i < 10; i++) {
                    try {
                        Thread.sleep((long)(Math.random()*1000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Thread1 is running");
                }
                isThread1 = false;
                ThreadExecuteOrderTest.class.notify();
            }
        }
    }

    static class Thread2 implements Runnable{
        public void run() {
            synchronized (ThreadExecuteOrderTest.class){
                while (isThread1){
                    try {
                        ThreadExecuteOrderTest.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                for (int i = 0; i < 10; i++) {
                    try {
                        Thread.sleep((long)(Math.random()*1000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Thread2 is running");
                }
                isThread1 = true;
                ThreadExecuteOrderTest.class.notify();
            }
        }
    }

    public static void main(String[] args) {
        new Thread(new Thread1()).start();
        new Thread(new Thread2()).start();
    }
}
